/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head == nullptr || head->next == nullptr)
            return head;
        
        ListNode* pdum1 = new ListNode();
        pdum1->next = head;
        ListNode* pre = pdum1;
        ListNode* cur = head;

        ListNode* pdum2 = new ListNode();
        ListNode* pos = pdum2;

        while(cur)
        {
            ListNode* next = cur->next;
            if(cur->val >= x)
            {
                pos->next = cur;
                pos = pos->next;
                pre->next = next;
                cur = next;
            }
            else
            {
                pre = cur;
                cur = next;
            }
        }

        pos->next = nullptr;
        pre->next = pdum2->next;
        
        return pdum1->next;
    }
};
